package com.cn.util;

import com.cn.threadTask.ScheduleTask;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Component
@EnableScheduling
public class ScheduleUtil {
    // 线程存储器
    private static ConcurrentHashMap<String, ScheduledFuture> map = new ConcurrentHashMap<>(30);

    @Resource
    private ThreadPoolTaskScheduler threadSchedulePool;


    /**
     * 线程池
     * @return ThreadPoolTaskScheduler
     */
    @Bean("threadSchedulePool")
    public ThreadPoolTaskScheduler setThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(10);
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        return threadPoolTaskScheduler;
    }

    /**
     * 添加定时任务
     * @return true
     */
    public boolean startTask(){
        ScheduledFuture<?> future = threadSchedulePool.schedule(new ScheduleTask(), new CronTrigger("0/5 * * * * *"));
        assert future != null;
        map.put("数据库查询",future);
        return true;
    }

    /**
     *  停止定时任务
     * @param taskID 指定定时任务
     * @return 结果
     */
    public boolean stopTask(String taskID){
        ScheduledFuture<?> future = map.get(taskID);
        future.cancel(true);
        map.remove(taskID);
        return true;
    }







}
